from datetime import datetime, timedelta

from django.http import HttpResponse
from django.shortcuts import render, redirect

# Create your views here.
from django.views.decorators.csrf import csrf_exempt

from app.models import User


def check_login(func):
    def inner(*args, **kwargs):
        if args[0].COOKIES.get("user"):
            return func(*args, **kwargs)
        else:
            return redirect("/login")

    return inner


@csrf_exempt
def login(request):
    print(request.method)
    if (request.method == "GET"):
        return render(request, "cookie/index.html")
    elif (request.method == "POST"):
        username = request.POST.get("username")
        password = request.POST.get("password")

        stu = User.objects.filter(username=username, password=password)
        print(stu)

        if stu:
            # 存储cookie
            response = redirect("/home/")
            response.set_cookie("user", username, expires=datetime.now() + timedelta(days=3))
            return response
        else:
            return render(request, "cookie/index.html")


@check_login
def home(request):
    #获取cookie
    username = request.COOKIES.get('user')
    print("username--{}".format(username))
    return render(request, "cookie/home.html")


def logout(request):
    # 删除cookie
    response = redirect("/home/")
    response.delete_cookie('user')
    return response

@check_login
def homelist(request):
    return HttpResponse("我是列表数据")